import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/modules/user'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'login',
      component: () => import('@/views/LoginView.vue'),
    },
    {
      path: '/map',
      name: 'map',
      component: () => import('@/views/MapView.vue'),
      children: [
        {
          path: '',
          name: 'mapBrowse',
          component: () => import('@/views/pages/MapBrowse.vue'),
        },
        {
          path: 'parcel-query',
          name: 'parcelQuery',
          component: () => import('@/views/pages/ParcelQuery.vue'),
        },
        {
          path: 'parcel-edit',
          name: 'parcelEdit',
          component: () => import('@/views/pages/ParcelEdit.vue'),
        },
        {
          path: 'statistics',
          name: 'statistics',
          component: () => import('@/views/pages/StatisticsAnalysis.vue'),
        },
      ],
    },
  ],
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore()

  // 如果目标是登录页，直接放行
  if (to.path === '/') {
    next()
    return
  }

  // 检查用户是否已登录
  if (!userStore.isLogin) {
    // 如果需要认证但用户未登录，重定向到登录页
    next('/')
  } else {
    // 其他情况正常导航
    next()
  }
})

export default router
